package cn.edu.jxau.test;

/**
 * binary search
 * @author 付大石
 */
public class Main {

    public static void main(String[] args) {
        
        System.out.println(sqrt(4));
        System.out.println(sqrt(9));
        System.out.println(sqrt(16));
    }

    /**
     * 用二分法的方式开平方根
     * @param x
     * @return
     */
    public static double sqrt(double x) {

        if (x < 0) {
            throw new RuntimeException(String.format("x=%d,负数不能开平方根", x));
        }
        double low = 0;
        double high = x;
        double mid = (low + high) / 2;
        double t = mid * mid - x;
        double precision = 1e-15;
        while (Math.abs(t) > precision) { // 进度不符，继续逼近
            if (t > 0) {
                high = mid;
            } else {
                low = mid;
            }
            mid = (low + high) / 2;
            t = mid * mid - x;
        }
        return mid;
    }
}
